<template>
  <div class="document-parser">
    <parser-header 
      title="Document Parser" 
      @refresh="fetchDocuments"
      :loading="loading"
    />
    
    <div class="parser-content">
      <document-list-section 
        :documents="documents"
        :loading="loading"
        :current-page="currentPage"
        :page-size="pageSize"
        :total-documents="totalDocuments"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @parse-document="parseDocument"
        @view-questions="viewQuestions"
      />
      
      <div v-if="!selectedDocument" class="empty-state-container">
        <empty-state 
          :message="emptyStateMessage"
          icon="mdi-file-document-outline"
          @go-to-upload="goToUpload"
        />
      </div>
      
      <div v-else class="parser-workspace">
        <div class="document-header">
          <h3>{{ selectedDocument.title }}</h3>
          <div class="document-status">
            <el-tag
              :type="getStatusColor(selectedDocument.parser_status)"
              size="small"
              class="status-chip"
            >
              {{ getStatusText(selectedDocument.parser_status) }}
            </el-tag>
          </div>
        </div>
        
        <div class="parser-actions">
          <el-button type="primary" @click="openQuestionsDialog" :disabled="!canViewQuestions">
            <el-icon><QuestionFilled /></el-icon>
            Questions
          </el-button>
          <el-button type="success" @click="openImportDialog" :disabled="!canImport">
            <el-icon><Download /></el-icon>
            Import
          </el-button>
          <el-button type="warning" @click="reparseDocument" :disabled="isProcessing">
            <el-icon><RefreshRight /></el-icon>
            Reparse
          </el-button>
        </div>
        
        <div class="document-content">
          <div v-if="isProcessing" class="content-container processing-indicator">
            <el-progress type="circle" :percentage="0" :indeterminate="true"></el-progress>
            <p>Processing document...</p>
          </div>
          <div v-else-if="selectedDocument.parser_status === 'failed'" class="content-container error-message">
            <el-icon size="large" color="#F56C6C"><CircleCloseFilled /></el-icon>
            <p>Failed to parse document. Please try again or check the document format.</p>
          </div>
          <div v-else-if="selectedDocument.parser_status === 'completed'" class="content-container">
            <div class="success-header">
              <el-icon size="large" color="#67C23A"><CircleCheckFilled /></el-icon>
              <p>Document parsed successfully. {{ selectedDocument.questions_count || 0 }} questions found.</p>
            </div>
            
            <div v-if="selectedDocument.questions_count > 0" class="questions-preview">
              <h4>Questions Preview</h4>
              <div class="questions-list">
                <p class="placeholder-text">Click the "Questions" button above to view all parsed questions.</p>
              </div>
            </div>
          </div>
          <div v-else class="content-container placeholder">
            <p>Select a document and click "Parse" to extract questions.</p>
          </div>
        </div>
      </div>
    </div>
    
    <!-- Dialogs -->
    <questions-dialog 
      v-model="showQuestionsDialog"
      :document="selectedDocument"
      @save="handleQuestionsSave"
    />
    
    <import-dialog
      v-model="showImportDialog"
      @import="handleImport"
    />
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { QuestionFilled, Download, RefreshRight, CircleCloseFilled, CircleCheckFilled } from '@element-plus/icons-vue'
import ParserHeader from './parser/ParserHeader.vue'
import DocumentListSection from './parser/DocumentListSection.vue'
import EmptyState from './parser/EmptyState.vue'
import QuestionsDialog from './parser/QuestionsDialog.vue'
import ImportDialog from './parser/ImportDialog.vue'
import http from '../utils/axios'  // 导入axios实例

export default {
  name: 'DocumentParser',
  
  components: {
    ParserHeader,
    DocumentListSection,
    EmptyState,
    QuestionsDialog,
    ImportDialog,
    QuestionFilled,
    Download,
    RefreshRight,
    CircleCloseFilled,
    CircleCheckFilled
  },
  
  setup() {
    const router = useRouter()
    
    // State
    const documents = ref([])
    const selectedDocument = ref(null)
    const showQuestionsDialog = ref(false)
    const showImportDialog = ref(false)
    const loading = ref(false)
    const error = ref(null)
    
    // Pagination
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalDocuments = ref(0)
    
    // Computed properties
    const emptyStateMessage = computed(() => {
      if (loading.value) return 'Loading documents...'
      if (error.value) return `Error: ${error.value}`
      if (documents.value.length === 0) return 'No documents found. Upload a document to start parsing.'
      return 'Select a document to start parsing'
    })
    
    const isProcessing = computed(() => {
      return selectedDocument.value && selectedDocument.value.parser_status === 'processing'
    })
    
    const canViewQuestions = computed(() => {
      return selectedDocument.value && 
             selectedDocument.value.parser_status === 'completed' &&
             (selectedDocument.value.questions_count > 0)
    })
    
    const canImport = computed(() => {
      return selectedDocument.value && 
             selectedDocument.value.parser_status === 'completed' &&
             (selectedDocument.value.questions_count > 0)
    })
    
    // Methods
    const fetchDocuments = async () => {
      try {
        loading.value = true
        error.value = null
        
        // 实际API调用
        const response = await http.get('/documents/', {
          params: { 
            page: currentPage.value, 
            page_size: pageSize.value,
            timestamp: new Date().getTime() // 添加时间戳防止缓存
          }
        })
        
        // 处理响应数据
        if (Array.isArray(response.data)) {
          documents.value = response.data.map(doc => ({
            ...doc,
            parsing: false,
            reparsing: false,
            parser_status: doc.parser_status || 'pending'
          }))
          totalDocuments.value = response.data.length
        } else if (response.data && response.data.results && Array.isArray(response.data.results)) {
          documents.value = response.data.results.map(doc => ({
            ...doc,
            parsing: false,
            reparsing: false,
            parser_status: doc.parser_status || 'pending'
          }))
          totalDocuments.value = response.data.count || 0
        } else {
          documents.value = []
          totalDocuments.value = 0
          console.warn('Unexpected response format:', response.data)
        }
        
        // 获取每个文档的解析状态
        if (Array.isArray(documents.value)) {
          await Promise.all(documents.value.map(doc => fetchParserStatus(doc)))
        }
        
        loading.value = false
      } catch (err) {
        console.error('Error fetching documents:', err)
        error.value = 'Failed to load documents'
        loading.value = false
      }
    }
    
    // 获取文档的解析状态
    const fetchParserStatus = async (document) => {
      try {
        if (!document || !document.id) {
          console.warn('Invalid document object:', document)
          return
        }
        
        const params = { 
          document_id: document.id,
          timestamp: new Date().getTime()
        }
        
        const response = await http.get('/parser/tasks/', { params })
        
        if (response.data && Array.isArray(response.data) && response.data.length > 0) {
          const latestTask = response.data[0]
          
          document.parser_status = latestTask.status || 'pending'
          document.questions_count = latestTask.questions_count || 0
        }
      } catch (error) {
        console.error('获取解析状态失败:', document.title, error)
      }
    }
    
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
      fetchDocuments()
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchDocuments()
    }
    
    const parseDocument = async (document) => {
      try {
        if (!document || !document.id) {
          error.value = 'Invalid document'
          return
        }
        
        selectedDocument.value = document
        selectedDocument.value.parser_status = 'processing'
        
        // 实际API调用
        const response = await http.post(`/parser/documents/${document.id}/parse/`, {
          auto_detect_answers: true
        })
        
        if (response.data && response.data.success) {
          console.log('Document parsing request submitted')
          
          // 定时检查解析状态
          checkParsingStatus(document)
        } else {
          selectedDocument.value.parser_status = 'failed'
          error.value = (response.data && response.data.message) ? response.data.message : 'Parsing failed'
        }
      } catch (err) {
        console.error('Error parsing document:', err)
        selectedDocument.value.parser_status = 'failed'
        error.value = err.response?.data?.message || 'Failed to parse document'
      }
    }
    
    // 定时检查解析状态
    const checkParsingStatus = (document) => {
      if (!document || !document.id) return
      
      const checkInterval = setInterval(async () => {
        try {
          await fetchParserStatus(document)
          
          if (document.parser_status !== 'processing') {
            clearInterval(checkInterval)
            
            // 如果是当前选中的文档，更新状态
            if (selectedDocument.value && selectedDocument.value.id === document.id) {
              selectedDocument.value.parser_status = document.parser_status
              selectedDocument.value.questions_count = document.questions_count
            }
          }
        } catch (error) {
          console.error('检查解析状态失败:', error)
          clearInterval(checkInterval)
        }
      }, 3000)
      
      // 最多检查10分钟
      setTimeout(() => {
        clearInterval(checkInterval)
      }, 10 * 60 * 1000)
    }
    
    const reparseDocument = async () => {
      if (!selectedDocument.value || !selectedDocument.value.id) return
      
      try {
        selectedDocument.value.parser_status = 'processing'
        
        // 实际API调用
        const response = await http.post(`/parser/documents/${selectedDocument.value.id}/reparse/`, {
          auto_detect_answers: true
        })
        
        if (response.data && response.data.success) {
          console.log('Document reparsing request submitted')
          
          // 定时检查解析状态
          checkParsingStatus(selectedDocument.value)
        } else {
          selectedDocument.value.parser_status = 'failed'
          error.value = (response.data && response.data.message) ? response.data.message : 'Reparsing failed'
        }
      } catch (err) {
        console.error('Error reparsing document:', err)
        selectedDocument.value.parser_status = 'failed'
        error.value = err.response?.data?.message || 'Failed to reparse document'
      }
    }
    
    const viewQuestions = async (document) => {
      try {
        if (!document || !document.id) {
          error.value = 'Invalid document'
          return
        }
        
        selectedDocument.value = document
        openQuestionsDialog()
      } catch (err) {
        console.error('Error viewing questions:', err)
        error.value = err.response?.data?.message || 'Failed to view questions'
      }
    }
    
    const openQuestionsDialog = () => {
      showQuestionsDialog.value = true
    }
    
    const openImportDialog = () => {
      showImportDialog.value = true
    }
    
    const handleQuestionsSave = (questions) => {
      console.log('Saving questions:', questions)
      showQuestionsDialog.value = false
    }
    
    const handleImport = async (data) => {
      try {
        const response = await http.post('/parser/exercises/import/', {
          document_id: selectedDocument.value.id,
          title: data.title || `${selectedDocument.value.title} - Exercise Set`,
          description: data.description || `Imported from ${selectedDocument.value.title}`,
          is_public: data.is_public || false
        })
        
        if (response.data && response.data.success) {
          console.log('Successfully imported to exercises')
          showImportDialog.value = false
          
          // 可选：导入成功后跳转到练习详情页
          if (response.data.exercise_set_id) {
            router.push(`/dashboard/exercises/${response.data.exercise_set_id}`)
          }
        } else {
          error.value = (response.data && response.data.message) ? response.data.message : 'Import failed'
        }
      } catch (err) {
        console.error('Error importing to exercises:', err)
        error.value = err.response?.data?.message || 'Failed to import to exercises'
      }
    }
    
    const goToUpload = () => {
      router.push('/dashboard/upload')
    }
    
    const getStatusColor = (status) => {
      switch (status) {
        case 'completed': return 'success'
        case 'processing': return 'info'
        case 'failed': return 'danger'
        default: return 'info'
      }
    }
    
    const getStatusText = (status) => {
      switch (status) {
        case 'completed': return 'Completed'
        case 'processing': return 'Processing'
        case 'failed': return 'Failed'
        default: return 'Pending'
      }
    }
    
    // Initialize
    fetchDocuments()
    
    return {
      documents,
      selectedDocument,
      showQuestionsDialog,
      showImportDialog,
      loading,
      error,
      currentPage,
      pageSize,
      totalDocuments,
      emptyStateMessage,
      isProcessing,
      canViewQuestions,
      canImport,
      fetchDocuments,
      handleSizeChange,
      handleCurrentChange,
      parseDocument,
      reparseDocument,
      viewQuestions,
      openQuestionsDialog,
      openImportDialog,
      handleQuestionsSave,
      handleImport,
      goToUpload,
      getStatusColor,
      getStatusText
    }
  }
}
</script>

<style scoped>
.document-parser {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.parser-content {
  display: flex;
  height: calc(100vh - 64px - 64px);
  overflow: hidden;
}

.empty-state-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.parser-workspace {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.document-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.status-chip {
  margin-left: 8px;
}

.parser-actions {
  margin: 16px 0;
  display: flex;
  gap: 8px;
}

.document-content {
  margin-top: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  height: 320px; /* Reduced from 400px to 320px */
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.content-container {
  padding: 16px;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow-y: auto; /* Add vertical scrolling */
}

.success-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
  text-align: center;
}

.questions-preview {
  width: 100%;
  max-width: 800px;
  margin-top: 20px;
  border-top: 1px solid #e0e0e0;
  padding-top: 20px;
}

.questions-list {
  margin-top: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 16px;
  height: 150px; /* Reduced from 200px to 150px */
  overflow-y: auto;
  background-color: #f9f9f9;
}

.placeholder-text {
  color: #757575;
  font-style: italic;
  text-align: center;
}

.processing-indicator,
.error-message,
.success-message,
.placeholder {
  text-align: center;
}

.error-message {
  color: #f44336;
}

.success-message {
  color: #4caf50;
}
</style> 